﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace JAAF.UI
{
    /// <summary>
    /// Implements the <see cref="ICommand"/> interface
    /// and forwards the execution to a function delegate.
    /// </summary>
    public class DelegateCommand: IUICommand
    {
        #region Instance Data

        private Action<object> m_dgExecutionHandler;

        private Func<bool> m_dgCanExecute;

        private bool m_bIsEnabled;

        #endregion


        public DelegateCommand(Action<object> _dgExecutionHandler, Func<bool> _dgCanExecute = null)
        {
            m_dgExecutionHandler = _dgExecutionHandler;
            m_dgCanExecute = _dgCanExecute;

            if (m_dgCanExecute == null)
                m_bIsEnabled = true;
        }

        public bool CanExecute(object parameter)
        {
            if (m_dgCanExecute == null)
                return m_bIsEnabled;
            else
                return m_dgCanExecute();
        }

        public event EventHandler CanExecuteChanged;

        /// <summary>
        /// This method fires the <see cref="DelegateCommand.CanExecuteChanged"/> event.
        /// </summary>
        public void OnCanExecuteChanged()
        {
            if (this.CanExecuteChanged != null)
                this.CanExecuteChanged(this, EventArgs.Empty);
        }


        public void Execute(object _oParameter)
        {
            m_dgExecutionHandler(_oParameter);
        }

        public bool IsEnabled
        {
            get
            {
                return m_bIsEnabled;
            }

            set
            {
                if (value == m_bIsEnabled)
                    return;

                m_bIsEnabled = value;

                if (this.CanExecuteChanged != null)
                    this.CanExecuteChanged(this, EventArgs.Empty);

            }
        }

        public virtual string Caption
        {
            get;

            set;
        }

        public virtual string Documentation
        {
            get;

            set;
        }
    }
}
